﻿using AutoMapper;
using B.S.Base.Write.API.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class AddRoleCommandHandLer : IRequestHandler<AddRoleCommand, APIResult<int>>
    {
     private readonly   IBaseRepostiy<RoleModel> _roleModel;
        private readonly IMapper _mapper;

        public AddRoleCommandHandLer(IBaseRepostiy<RoleModel> _roleModel, IMapper mapper)
        {
            this._roleModel = _roleModel;
            this._mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
           var query= await _roleModel.GetAll().FirstOrDefaultAsync(x=>x.RoleName == request.RoleName&&x.IsDeleted==false);
            {
                if(query != null)
                {
                    return new APIResult<int>
                    {
                        Code = ResultCode.Fail,
                        Message = "角色重复"
                    };
                }
            }
            var list=_mapper.Map<RoleModel>(request);
        
            list.CreateUserTime = DateTime.Now;
             await _roleModel.AddAsync(list);
            return new APIResult<int>
            {
                Code = ResultCode.Ok,
                Data = 1,
                Message = "添加成功"
            };
        }
    }
}
